package com.sbj.config;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.zhxu.bs.BeanSearcher;
import cn.zhxu.bs.util.MapBuilder;
import cn.zhxu.bs.util.MapUtils;
import com.sbj.dto.res.ExtensionRes;
import com.sbj.dto.res.MemberStoreRes;
import com.sbj.entity.Income;
import com.sbj.service.ExtensionService;
import com.sbj.service.IIncomeService;
import com.zmh.framework.constants.Constants;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * @author summer
 * @version 1.0
 * @date 2024/9/7 16:20
 */
@Configuration
@Slf4j
@AllArgsConstructor
public class ExtensionScheduler {


    private final BeanSearcher beanSearcher;

    //收入明细 type=3
    private final IIncomeService incomeService;

    @Scheduled(cron = "0 50 23 * * ?")
    public void run(){
        //推广比例
        List<Income> incomeList= ListUtil.list(true);
        MapBuilder field = MapUtils.builder().field(ExtensionRes::getType, Constants.ONE);
        ExtensionRes extensionRes = beanSearcher.searchFirst(ExtensionRes.class, field.build());
        Map<String, Object> build = MapUtils.builder().field(MemberStoreRes::getCompleteTime).sql("DATE($1) =CURDATE()").build();
        List<MemberStoreRes> memberStoreLists = beanSearcher.searchList(MemberStoreRes.class, build);
        BigDecimal div;
        if(ObjectUtil.isNotEmpty(extensionRes)){
             div = NumberUtil.div(new BigDecimal(extensionRes.getScale()), 100);
        } else {
            div = BigDecimal.ZERO;
        }
        memberStoreLists.forEach(memberStoreRes -> {
            Income income = new Income();
            income.setName(extensionRes.getName());
            income.setMemberId(memberStoreRes.getBuyerId());
            income.setType(3);
            BigDecimal bigDecimal = NumberUtil.mul(div, memberStoreRes.getGoodsPrice()).setScale(2, BigDecimal.ROUND_HALF_UP);
            income.setPrice(bigDecimal);
            incomeList.add(income);
        });
        log.info("推广信息:{}",System.currentTimeMillis());
        incomeService.saveBatch(incomeList);
    }
}
